const http = require("http");
const {httpReadFile,httpReadFileWithData} = require("./utils/file-util")
const server = http.createServer();

const url = require("url")

server.listen(3000,function (){
    console.log("留言板项目启动成功")
})

const list = [
    {name:"刘备",content:"我二弟天下无敌",date: new Date()},
    {name:"刘备",content:"接着奏乐",date: new Date()},
]

server.on("request",function(request,response){
    const {pathname,query} = url.parse(request.url,true)
    if (pathname === "/"){
        httpReadFileWithData("./views/index.html",response,{list})
    } 

    else if(pathname === "/add"){
        httpReadFile("./views/add.html",response)
    }

    else if (pathname === "/save"){
        // 代表我们进行一个留言发布的功能
        list.push(query)
        // 需要跳转到首页
        // 状态码是302 代表重定向
        response.statusCode = 302
        response.setHeader("Location","/")
        response.end()
    }

    // 允许用户访问node_modules下的内容
    else if(pathname.startsWith('/node_modules')){
        // /node_modules/bootstrap/dist/css/bootstrap.min.css
        httpReadFile("."+pathname,response)
    }
    
    else {
        httpReadFile("./views/404.html",response)
    }
})